﻿#include "cd33comm.h"

CD33Comm::CD33Comm(QObject *parent)
    : QObject(parent),
      m_comPort("COM1"),
      m_baudRate(QSerialPort::Baud9600),
      m_dataBits(QSerialPort::Data8),
      m_parity(QSerialPort::NoParity),
      m_stopBits(QSerialPort::OneStop),
      m_serialPort(nullptr),
      m_state(0)
{

}

bool CD33Comm::openPort(QString port)
{
    m_comPort = port;
    if(m_serialPort)
     {
         m_serialPort->close();
         delete m_serialPort;
     }
     m_serialPort = new QSerialPort(m_comPort, this);
     if(m_serialPort->open(QIODevice::ReadWrite))
     {
         m_serialPort->setBaudRate(m_baudRate);
         m_serialPort->setDataBits(static_cast<QSerialPort::DataBits> (m_dataBits));
         m_serialPort->setParity(static_cast<QSerialPort::Parity>(m_parity));
         m_serialPort->setStopBits(static_cast<QSerialPort::StopBits>(m_stopBits));
         m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
         m_serialPort->clearError();
         m_serialPort->clear();
         return true;
     }
     return false;
}

void CD33Comm::getData()
{
    if(m_serialPort && m_serialPort->isWritable())
        {
            char a[9] = {};
            m_serialPort->write(a, 9);
        }
}

void CD33Comm::on_readyRead()
{
    QByteArray data = m_serialPort->readAll();
    QByteArray::const_iterator it;
    for (it = data.constBegin(); it != data.constEnd(); ++it)
    {
          stateMachine(*it);
    }
}

void CD33Comm::stateMachine(char x)
{
    switch (m_state)
    {
    case 0:
        if(x == 0x02)
        {
            m_state = 1;
            m_buffer.clear();
        }
        break;
    case 1:
        if(x == 0x03)
        {
            m_state = 0;
            bool ok;
            double value = m_buffer.toDouble(&ok);
            if(ok)
            {
                emit dataReceived(value);
            }
        }
        else
        {
            m_buffer += x;
        }
    }
}
